#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.contrib.sessions.backends.cache import SessionStore
from django.shortcuts import get_object_or_404

from cmdb_auths.models import UserAuthCmdb, AuthGroup


def auth_class(user):
    """
    修改session权限
    刷新页面权限即生效
    :return:
    """
    auth_group_data = {}
    auth_list = [
        "select_host",
        "edit_host",
        "update_host",
        "add_host",
        "bat_add_host",
        "delete_host",
        "project_name",
        "add_user",
        "edit_user",
        "edit_pass",
        "delete_user",
        "add_department",
        "add_idc",
        "edit_idc",
        "del_idc",
        "setup_system",
        "upload_system",
        "salt_keys",
        "project_auth",
        "auth_log",
        "add_project",
        "edit_project",
        "del_project",
        "select_idc",
        "auth_project",
        "auth_highstate",
        "cmdb_log",
        "server_audit",
    ]

    user_name = user
    if user_name:
        group_auths = user_name.authgroup_set.all().filter(enable=True)
        # 权限
        for group_auth in group_auths:
            pk = str(group_auth.pk)
            data = AuthGroup.objects.get(pk=pk)
            try:
                auth_info = UserAuthCmdb.objects.get(group_name=data)

                for i in auth_list:
                    try:
                        s = getattr(auth_info, i)
                        if s:
                            print(auth_group_data.get(i))
                            auth_group_data[i] = s

                    except AttributeError:
                        pass
            except UserAuthCmdb.DoesNotExist:
                pass
        return auth_group_data
    else:
        return auth_group_data


def auth_session_clsss(auth_group_id):
    """ 更新角色组所有用户权限(session信息) """
    auth_group_obj = get_object_or_404(AuthGroup, pk=auth_group_id)
    auth_group_obj_users = auth_group_obj.group_user.all()

    for user in auth_group_obj_users:
        if user.session_key:
            s = SessionStore(session_key=user.session_key)
            s['fun_auth'] = auth_class(user)
            s.save()
    return None
